package com.wuzf.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import org.springframework.jdbc.core.JdbcTemplate;

import com.alibaba.druid.pool.DruidDataSource;

public class JdbcTemplateUtils {
	private static final String className = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3336/shiro";
	private static final String username = "root";
	private static final String password = "123456";
	private static JdbcTemplate template;
	
	private Connection connect;
	private PreparedStatement pst;
	
	public static JdbcTemplate JdbcTemplate() {
		if (template == null) {
			return createDataSource();
		}
		return template;
	}
	
	
	public static JdbcTemplate createDataSource() {
		DruidDataSource ds = new DruidDataSource();
		ds.setDriverClassName(className);
		ds.setUrl(url);
		ds.setUsername(username);
		ds.setPassword(password);
		return new JdbcTemplate(ds);
	}
	
	public PreparedStatement getConnect(String sql) {
		try {
			Class.forName(className);
			connect = DriverManager.getConnection(url, username, password);
			pst = connect.prepareStatement(sql);
			return pst;
		} catch (Exception e) {
			e.printStackTrace();
			return pst;
		}
	}
	
	public void close() {
		try {
			if (connect != null) {
				connect.close();
			}
			if (pst != null) {
				pst.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}	
